import axios from 'axios'
import { Message } from 'element-ui'
import Crypto from '@/utils/crypto'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: '/wzh' // url = base url + request url
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    config.headers['clientId'] = Crypto.encrypt('HzMgVzjm9ujx7HsNJJz1r8YSIR620J')
    config.headers['clientSecret'] = Crypto.encrypt('6NWSKln1OPRbEjM18tFWVmuF1ZbEES')
    config.headers['sign'] = Crypto.encrypt('HzMgVzjm9ujx7HsNJJz1r8YSIR620J6NWSKln1OPRbEjM18tFWVmuF1ZbEES')
    // config.headers['responseType'] = 'blob'

    // config.headers['X-Access-Token'] = token
    // config.headers['access_token'] = Crypto.encrypt(token)
    config.headers['accessToken'] = Crypto.encrypt(token)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async response => {
    console.log(response)
    if (typeof response.data === 'string') {
      return response.data
    }
    const res = response.data
    if (res.code == 0) {
      return res
    }
    Message.error(res.msg)

    if (res.code == 400) {
      await store.dispatch('user/logout')
      return
    }
    return Promise.reject(res.msg)
  },
  async error => {
    const response = error.response
    if (response) {
      if (response.status === 401) {
        Message.error(response.data.msg)
        await store.dispatch('user/logout')
      } else if (response.status === 500) {
        Message.error(response.data.message)
      } else {
        Message.error(response.data.message)
      }
    }
    return Promise.reject(error)
  }
)

const get = (url, params = {}) => service({
  method: 'get',
  url,
  params
})
const post = (url, data = {}) => service({
  method: 'post',
  url,
  data
})
// 表单查询
const postFormData = (url, data) => {
  const formData = new FormData()
  for (const dataKey in data) {
    formData.append(dataKey, data[dataKey] || '')
  }
  return service({
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    url,
    data: formData
  })
}
const postUpload = (url, file) => {
  const data = new FormData()
  data.append('file', file)
  return service({
    method: 'post',
    url,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data
  })
}

const put = (url, params = {}, data = {}) => service({
  method: 'put',
  url,
  params,
  data
})

const del = (url, params = {}, data = {}) => service({
  method: 'delete',
  url,
  params,
  data
})
const downloadFile = (url, fileName) => {
  const a = document.createElement('a')
  fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
    a.href = URL.createObjectURL(blob)
    console.log(a.href)
    a.download = fileName
    // a.download = url.split('/')[url.split('/').length -1] //  // 下载文件的名字
    document.body.appendChild(a)
    a.click()

    // 在资源下载完成后 清除 占用的缓存资源
    window.URL.revokeObjectURL(a.href)
    document.body.removeChild(a)
  })
}

const exportFile = (url) => {
  if (!url) return Message.error('暂无导出接口')
  window.open(`http://zhmsbgapi.wenkangkeji.com/zhmsbg/${url}`, '_self')
}

export {
  postFormData,
  postUpload,
  get,
  post,
  put,
  del,
  exportFile,
  downloadFile
}
export default service
